package com.ming.closeto.base;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.ming.closeto.listener.OnRequestPermissionListener;

import java.util.ArrayList;
import java.util.List;

public class BasePermissionActivity extends Activity {

    public static final String TAG = "BasePermissionActivity";
    /**
     * 1. 请求权限
     *    checkPermissions: 权限数组  回调code  结果回调
     * 2. 处理权限
     */
    private int permissionRequestCode;
    private List<String> mListPermissions = new ArrayList<>();
    private OnRequestPermissionListener listener;

    // 请求权限
    protected void checkPermissions(String [] permissions, int requestCode, OnRequestPermissionListener listener) {
        // 判断不能为空
        if (permissions != null && permissions.length != 0) {
            permissionRequestCode = requestCode;
            this.listener = listener;
            // 先去遍历你的权限 相机/电话/SD卡 List装载未申请的权限
            for (int i=0; i<permissions.length; i++) {
                // 判断未申请，就装起来
                if (!checkSelfPermissions(permissions[i])) {
                    mListPermissions.add(permissions[i]);
                }
            }
            Log.i(TAG, "遍历完成");
            // 遍历完之后申请
            applyPermissions();
        } else {
            Log.i(TAG, "权限数组未空");
//            listener.onNullPermission();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == permissionRequestCode) {
            Log.i(TAG, "接收到回调");
            if (grantResults.length > 0) {
                if (grantResults.length > 0) {
                    listener.onSuccessful(grantResults);
                } else {
                    listener.onFailure();
                }
            }
        }
    }

    // 检查权限
    private boolean checkSelfPermissions(String permissions) {
        if (ActivityCompat.checkSelfPermission(this, permissions)  == PackageManager.PERMISSION_GRANTED) {
            return true;
        };
        return false;
    }

    // 申请权限
    private void applyPermissions() {
        // 判断权限集合是否未空
        if (!mListPermissions.isEmpty()) {
            // 申请权限
            int size = mListPermissions.size();
            ActivityCompat.requestPermissions(this, mListPermissions.toArray(new String[size]), 100);
            Log.i(TAG,"请求权限");
            mListPermissions.clear();
        } else {
            listener.onFailure();
        }
    }
}
